module Trifle
  module Ruby
    class JsonTransform

      def self.transform(payload)
        payload = payload.to_hash if payload.class == Object
        return payload unless payload.class == Hash
        transform_hash(payload, deep: true) { |hash, key, value|
          begin
            hash[key.to_s] = value.to_s.clone.force_encoding('iso-8859-1').encode('utf-8')
          rescue
            hash[key.to_s] = value.clone
          end
        }.with_indifferent_access
      end

      # https://gist.github.com/dbenhur/1070399
      def self.transform_hash(original, options={}, &block)
        options[:safe_descent] ||= {}
        new_hash = {}
        options[:safe_descent][original.object_id] = new_hash
        original.inject(new_hash) { |result, (key,value)|
          if (options[:deep] && Hash === value)
            value = options[:safe_descent].fetch( value.object_id ) {
              transform_hash(value, options, &block)
            }
          end
          block.call(result,key,value)
          result
        }
      end
    end
  end
end
